package com.b.sts.service.impl;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.b.sts.entity.GraduateEntity;
import com.b.sts.exception.FailException;
import com.b.sts.service.CommService;
import com.b.sts.service.UserService;
import com.b.sts.util.LoggerUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;


@Service
public class CommServiceImpl implements CommService {

    @Value("${b.file.baseDir}")
    String baseDir;
    @Resource
    UserService userService;

    @Override
    public String upload(MultipartFile file) {
        try {
            String resource = System.currentTimeMillis() + file.getOriginalFilename();
            String path = baseDir + resource;
            createFatherDir(baseDir);
            file.transferTo(Paths.get(path));
            return resource;
        } catch (IOException e) {
            e.printStackTrace();
            throw new FailException("上传文件发生错误");
        }
    }

    @Override
    public ResponseEntity<FileSystemResource> get(String url) {
        FileSystemResource file = new FileSystemResource(baseDir + url);
        if (!file.exists()) {
            return null;
        }
        String contentDisposition = ContentDisposition.builder("attachment")
                .filename(Optional.ofNullable(file.getFilename()).orElse("未知文件"))
                .build()
                .toString();
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(file);
    }

    @SneakyThrows
    @Override
    public String uploadForm(MultipartFile file) {
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        List<GraduateEntity> list = reader.readAll(GraduateEntity.class);
        userService.saveGraduateData(list);
        return null;
    }


    private void createFatherDir(String path) {
        File f = new File(path);
        if (!f.exists()) {
            f.mkdirs();
            LoggerUtil.info("不存在该文件目录:" + path, CommServiceImpl.class);
        }
    }
}
